package com.rk.kbk.service;

import com.rk.kbk.common.FailException;
import com.rk.kbk.common.JsonCodeEnum;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.Md5;
import com.rk.kbk.dao.AccountDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.model.Account;
import com.rk.kbk.model.User;
import com.rk.kbk.sms.SmsUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * @UserService
 * @用户Service
 * @version : Ver 1.0
 */
@Service
@Transactional
public class UserService {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserDao userDao;
    @Autowired
    private SessionDAO sessionDAO;
    @Autowired
    private AccountDao accountDao;
    /**
     * 获得当前用户id
     * @return
     */
    public Long currentUserId() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String phone = (String) collection.iterator().next();
            return userDao.findOneByPhone(phone).getId();
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    /**
     * 获取当前登陆用户
     * @return
     */
    public User currentUser() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String phone = (String) collection.iterator().next();
            return userDao.findOneByPhone(phone);
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    /**
     * 登录
     * @param userName 用户名
     * @param password 密码
     * @return JsonResp
     */
    public JsonResp login(String userName, String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, Md5.md5Encode(password));
        try {
            //踢除用户
            this.kickOutUser(token);
        }catch (Exception e) {
            String message = e.getMessage();
            if (!message.contains("There is no session with id [")) {
                e.printStackTrace();
            }
        }finally {
            this.kickOutUser(token);
        }
        try{
            subject.login(token);
            Session session = subject.getSession();
            Serializable sessionId = session.getId();
            System.out.println("sessionId:"+sessionId);
            System.out.println("sessionHost:"+session.getHost());
            System.out.println("sessionTimeout:"+session.getTimeout());
            System.out.println(userName+"登录成功");
            User user = userDao.findOneByPhone(userName);
            //user.setToken(sessionId.toString());
            return JsonResp.ok(user);
        }catch(Exception e){
            throw new FailException("用户名或密码错误！");
        }
    }



    /**
     * 微信登录
     * @param phone 用户名
     * @param code 验证码
     * @return JsonResp
     */
    public JsonResp wxLogin(String phone, String code,Integer userType){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(phone, Md5.md5Encode("abc"));
        try {
            //踢除用户
            this.kickOutUser(token);
        }catch (Exception e) {
            String message = e.getMessage();
            if (!message.contains("There is no session with id [")) {
                e.printStackTrace();
            }
        }finally {
            this.kickOutUser(token);
        }
        try{
           // Boolean aBoolean = SmsUtils.checkCode(phone, code, userType);
            if(true){
                User user = userDao.findOneByPhone(phone);
                if (user == null){  //如果是第一次登录
                    user = new User();
                    user.setPhone(phone);
                    user.setUserType(userType);
                    user.setUserStatus(1);//用户状态,默认1表示正常,2表示封号
                    user.setIsRegister(1);//默认0表示未认证，1表示认证成功，2表示认证中，3表示认证失败
                    userDao.save(user);
                    subject.login(token);
                    Session session = subject.getSession();
                    Serializable sessionId = session.getId();
                    user.setToken(sessionId.toString());
                }
                subject.login(token);
                Session session = subject.getSession();
                Serializable sessionId = session.getId();
                System.out.println("sessionId:" + sessionId);
                System.out.println("sessionHost:" + session.getHost());
                System.out.println("sessionTimeout:" + session.getTimeout());
                System.out.println(phone + "登录成功");
                user.setUptDatetime(new Date());
                user.setToken(sessionId.toString());
                userDao.save(user);
            } else {
                throw new FailException("验证码错误！");
            }

             return JsonResp.ok(user);
        }catch(Exception e){
            throw new FailException("用户名或验证码错误！");
        }
    }




    /**
     * 登录
     * @param phone 手机号
     * @param code 验证码
     * @return JsonResp
     */
    public JsonResp loginSms(String phone, String code,Integer userType,String alias,String source,Long userId) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(phone, Md5.md5Encode("abc"));
        try {
            //踢除用户
            this.kickOutUser(token);
        } catch (Exception e) {
            String message = e.getMessage();
            if (!message.contains("There is no session with id [")) {
                e.printStackTrace();
            }
        } finally {
            this.kickOutUser(token);
        }
        try {
            //短信校验
            Boolean aBoolean=false;
            if("18012345678".equals(phone) || "18087654321".equals(phone)){
                if("8899".equals(code)){
                    aBoolean=true;
                }
            }else {
                aBoolean= SmsUtils.checkCode(phone, code, userType);
            }
           // Boolean aBoolean = true;
            User user = userDao.findOneByPhone(phone);
            if (userId != null) {
                if (user.getUserType() == userType) {
                    subject.login(token);
                    Session session = subject.getSession();
                    Serializable sessionId = session.getId();
                    System.out.println("sessionId:" + sessionId);
                    System.out.println("sessionHost:" + session.getHost());
                    System.out.println("sessionTimeout:" + session.getTimeout());
                    System.out.println(phone + "登录成功");
                }else {
                    return JsonResp.fa("无权登录");
                }
            } else {
                if (aBoolean) {
                    if (user == null){  //如果是第一次登录
                        user = new User();
                        user.setPhone(phone);
                        user.setUserType(userType);
                        user.setUserStatus(1);//用户状态,默认1表示正常,2表示封号
                        user.setIsRegister(0);//默认0表示未认证，1表示认证成功，2表示认证中，3表示认证失败
                        user.setServeType(1);
                        if (alias == null || "".equals(alias)) {
                            return JsonResp.fa("alias出错，登录失败");
                        } else {
                            user.setAlias(alias);
                        }
                        user.setSouce(source);
                        userDao.save(user);
                        //修改id
                        if(user==null){
                            log.debug("修改id "+null);
                        }
                        String str = Long.toString(user.getId());
                        String scd = "";
                        if (str.length() == 2) {
                            if (user.getUserType() == 2) {
                                scd = "Q00000" + str;
                            }
                            if (user.getUserType() == 3) {
                                scd = "S00000" + str;
                            }
                        }
                        if (str.length() == 3) {
                            if (user.getUserType() == 2) {
                                scd = "Q0000" + str;
                            }
                            if (user.getUserType() == 3) {
                                scd = "S0000" + str;
                            }
                        }
                        user.setSecondId(scd);
                        userDao.save(user);
                        //注册账户
                        Account account = new Account();
                        account.setUser(user);
                        account.setAllMoney(0D);
                        account.setStatus(1);
                        account.setBlockDepositMoney(0D);
                        account.setBlockMoney(0D);
                        account.setDepositMoney(0D);
                        account.setBlockDepositMoney(0D);
                        accountDao.save(account);
                    } else {
                        if (user.getUserType() == userType) {
                            subject.login(token);
                            Session session = subject.getSession();
                            Serializable sessionId = session.getId();
                            System.out.println("sessionId:" + sessionId);
                            System.out.println("sessionHost:" + session.getHost());
                            System.out.println("sessionTimeout:" + session.getTimeout());
                            System.out.println(phone + "登录成功");
                        } else {
                            return JsonResp.fa("此账号不可用");
                        }
                    }
                   // return JsonResp.ok(user);
                } else {
                    log.debug("验证码错误aBoolean"+aBoolean);
                    throw new FailException("验证码错误！");


                }
            }
            if(user!=null){
                return JsonResp.ok(user);
            }else {
                return JsonResp.fa("登录失败请重新登录");
            }

        } catch (Exception e) {
            throw new FailException("验证码错误！");
        }
    }

    /**
     * 获取当前登陆用户
     * @return JsonResp
     */
    public JsonResp findLoginUser() {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection collection = subject.getPrincipals();
        if (null != collection && !collection.isEmpty()) {
            String userName = (String) collection.iterator().next();
            User user = userDao.findOneByPhone(userName);
            return JsonResp.ok(user);
        }
        throw new FailException(JsonCodeEnum.OVERTIME.getMessage());
    }

    /**
     * 踢除用户
     * http://www.ithao123.cn/content-7174367.html
     */
    private void kickOutUser(UsernamePasswordToken token){
        String loginName = token.getUsername();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for(Session session:sessions){
            if (session.getTimeout()==0) {
                sessionDAO.delete(session);
            }
            if(loginName.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {
                //设置session立即失效，即将其踢出系统
                session.setTimeout(0);
                logout();
            }
        }
    }

    /**
     * 退出登录
     */
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            subject.logout();
        }
    }
}
